108. 将有序数组转换为二叉搜索树
为保证权益,题目请参考 108. 将有序数组转换为二叉搜索树(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode *sortedArrayToBST(vector<int> &nums) {
return helper(nums, 0, nums.size()-1);
}
TreeNode*helper(vector<int>&nums, int l, int r){
if(l > r){
return nullptr;
}
int mid = (l+r)/2;
TreeNode*p = new TreeNode(nums[mid]);
p->left = helper(nums, l, mid-1);
p->right = helper(nums, mid+1, r);
return p;
}
};
int main() {
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34